//
//  STDSIAPTool.m
//  STDSVideo
//
//  Created by 2022_cgp on 2021/1/11.
//  Copyright © 2021 stdstb. All rights reserved.
//

#import "MAIAPTool.h"
#import "MAVipMealModel.h"

@implementation MAIAPTool

#pragma mark -- Singleton
+ (instancetype)shareTool {
    static MAIAPTool *manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manager = [self new];
    });
    return manager;
}

- (void)ma_requestAllProductWithCompletion:(void (^)(BOOL, NSString * _Nonnull))completion{
    NSDictionary *savedMeal = [kUserDefaults objectForKey:kSavedMeal];
    MAVipMealModel *model = [MAVipMealModel yy_modelWithJSON:savedMeal];
    NSMutableSet *set = [NSMutableSet setWithCapacity:model.item.count];
    if (savedMeal) {
        for (MAMealItemModel *itemModel in model.item) {
            if (itemModel.payType.intValue == 3) {
                [set addObject:itemModel.appleProductId];
            }
        };
    }
    [[XYStore defaultStore] requestProducts:set success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        NSLog(@"code %@ invalid %@", products, invalidProductIdentifiers);
        MABlock(completion, YES, @"商品请求成功");
    } failure:^(NSError *error) {
        NSLog(@"goodsError - %@", error);
        MABlock(completion, NO, @"商品请求失败");
    }];
}

- (void)ma_buyProductWithId:(NSString *)productId completion:(void (^)(BOOL, NSString * _Nonnull))completion{
    [SVProgressHUD showWithStatus:@"正在购买中..."];
    [[XYStore defaultStore] addPayment:productId success:^(SKPaymentTransaction *transaction) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            NSLog(@"购买成功");
            MABlock(completion, YES, @"购买成功");
        });
   
    } failure:^(SKPaymentTransaction *transaction, NSError *error) {
        [SVProgressHUD dismiss];
        if (error.code == SKErrorPaymentCancelled) {
            MABlock(completion, NO, @"已取消购买");
        } else {
            MABlock(completion, NO, error.localizedDescription);
        }
        return;
    }];
}

@end
